package com.nowcoder.community.controller;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
public class MessageController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;
    
    @RequestMapping(value = "/letter/list", method = RequestMethod.GET)
    @LoginRequired
    public String getLetterPage(Model model, Page page) {
        User loginUser = hostHolder.getUser();
        // 所有未读私信
        model.addAttribute("allLetterUnreadCount", messageService.findLetterUnreadCount(loginUser.getId(), null));

        // 所有未读通知数
        model.addAttribute("allNoticeUnreadCount", messageService.findNoticeUnreadCount(loginUser.getId(), null));

        // 会话的分页信息
        page.setRows(messageService.findConversationCount(loginUser.getId()));
        page.setPath("/letter/list");

        // 会话列表
        List<Message> conversationList = messageService.findConversations(loginUser.getId(), page.getLimit(), page.getOffset());
        // 会话VO列表
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message conversation : conversationList) {
                Map<String, Object> map = new HashMap<>();
                // 当前会话
                map.put("conversation", conversation);
                // 当前会话未读私信数
                map.put("unreadCount", messageService.findLetterUnreadCount(loginUser.getId(), conversation.getConversationId()));
                // 当前会话的目标用户
                map.put("target", getTargetByConversationId(conversation.getConversationId()));
                // 当前会话的私信总数
                map.put("letterCount", messageService.findLetterCount(conversation.getConversationId()));
                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);

        return "/site/letter";
    }

    private User getTargetByConversationId(String conversationId) {
        String[] s = conversationId.split("_");
        if (s.length != 2) {
            throw new IllegalArgumentException("参数错误！");
        }
        if (Integer.parseInt(s[0]) == hostHolder.getUser().getId()) {
            return userService.findUserById(Integer.parseInt(s[1]));
        } else {
            return userService.findUserById(Integer.parseInt(s[0]));
        }
    }

    @RequestMapping(value = "/letter/detail/{conversationId}", method = RequestMethod.GET)
    @LoginRequired
    public String getLetterDetail(Model model, Page page, @PathVariable("conversationId") String conversationId) {
        User loginUser = hostHolder.getUser();
        // 私信的分页信息
        page.setRows(messageService.findLetterCount(conversationId));
        page.setPath("/letter/detail/" + conversationId);

        // 私信列表
        List<Message> letterList = messageService.findLetters(conversationId, page.getLimit(), page.getOffset());
        if (letterList == null || letterList.isEmpty()) {
            return "redirect:/letter/list";
        } else {
            List<Map<String, Object>> letters = new ArrayList<>();
            List<Integer> ids = new ArrayList<>();
            for (Message letter : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", letter);
                map.put("fromUser", userService.findUserById(letter.getFromId()));
                letters.add(map);
                // 记录未读私信的id
                if (letter.getToId() == loginUser.getId() && letter.getStatus() == 0) {
                    ids.add(letter.getId());
                }
            }
            model.addAttribute("letters", letters);

            // 设置当前页码的所有未读私信为已读
            messageService.readMessage(ids);
        }

        // 私信的目标用户
        model.addAttribute("target", getTargetByConversationId(conversationId));

        return "/site/letter-detail";
    }

    @RequestMapping(value = "/letter/send", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String sendLetter(String toName, String content) {
        User loginUser = hostHolder.getUser();
        if (toName.equals(loginUser.getUsername())) {
            return CommunityUtil.getJSONString(1, "不能给自己发私信！");
        }
        User toUser = userService.findUserByUsername(toName);
        if (toUser == null) {
            return CommunityUtil.getJSONString(1, "该用户不存在！");
        }

        int formId = loginUser.getId();
        int toId = toUser.getId();
        Message message = new Message();
        message.setFromId(formId);
        message.setToId(toId);
        message.setConversationId(Math.min(formId, toId) + "_" + Math.max(formId, toId));
        message.setContent(content);
        message.setStatus(0);
        message.setCreateTime(new Date());
        messageService.addMessage(message);

        return CommunityUtil.getJSONString(0);
    }

    @RequestMapping(value = "/message/delete", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public void deleteMessage(int id) {
        messageService.deleteMessage(Collections.singletonList(id));
    }

    @RequestMapping(value = "/notice/list", method = RequestMethod.GET)
    @LoginRequired
    public String getNoticePage(Model model) {
        User loginUser = hostHolder.getUser();
        // 所有未读私信数
        model.addAttribute("allLetterUnreadCount", messageService.findLetterUnreadCount(loginUser.getId(), null));

        // 所有未读通知数
        model.addAttribute("allNoticeUnreadCount", messageService.findNoticeUnreadCount(loginUser.getId(), null));

        // 评论类通知
        model.addAttribute("commentNotice", getLatestNoticeVO(CommunityConstant.TOPIC_COMMENT));
        // 点赞类通知
        model.addAttribute("likeNotice", getLatestNoticeVO(CommunityConstant.TOPIC_LIKE));
        // 关注类通知
        model.addAttribute("followNotice", getLatestNoticeVO(CommunityConstant.TOPIC_FOLLOW));


        return "/site/notice";
    }

    // 获取某类型最新通知的VO
    private Map<String, Object> getLatestNoticeVO(String topic) {
        User loginUser = hostHolder.getUser();
        Message notice = messageService.findLatestNotice(loginUser.getId(), topic);
        Map<String, Object> noticeVO = new HashMap<>();
        noticeVO.put("notice", notice);
        noticeVO.put("noticeUnreadCount", messageService.findNoticeUnreadCount(loginUser.getId(), topic));
        noticeVO.put("noticeCount", messageService.findNoticeCount(loginUser.getId(), topic));

        if (notice != null) {
            String content = HtmlUtils.htmlUnescape(notice.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            noticeVO.put("fromUser", userService.findUserById((Integer) data.get("userId")));
            noticeVO.put("entityType", data.get("entityType"));
        }

        return noticeVO;
    }

    @RequestMapping(value = "/notice/detail/{topic}", method = RequestMethod.GET)
    @LoginRequired
    public String getNoticeDetail(Model model, Page page, @PathVariable("topic") String topic) {
        User loginUser = hostHolder.getUser();

        page.setRows(messageService.findNoticeCount(loginUser.getId(), topic));
        page.setPath("/notice/detail/" + topic);

        List<Message> noticeList = messageService.findNotices(loginUser.getId(), topic, page.getLimit(), page.getOffset());
        List<Map<String, Object>> notices = new ArrayList<>();
        // 记录当前页面所有未读通知的id
        List<Integer> ids = new ArrayList<>();
        if (noticeList == null || noticeList.isEmpty()) {
            return "redirect:/notice/list";
        } else {
            for (Message notice : noticeList) {
                if (notice.getStatus() == 0) {
                    ids.add(notice.getId());
                }

                Map<String, Object> map = new HashMap<>();
                map.put("notice", notice);
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("fromUser", userService.findUserById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("postId", data.get("postId"));
                notices.add(map);
            }
        }
        model.addAttribute("notices", notices);

        // 批量设置未读通知为已读
        messageService.readMessage(ids);

        return "/site/notice-detail";
    }

}
